<?php
namespace app\controllers;
use Yii;
use Redis;
use linslin\yii2\curl;
use yii\base\Response;
use yii\web\Controller;
class MainController extends Controller
{  
    public $redis        = null;
    public $enableCsrfValidation = false;
    public $_message ;
//    public $layout = 'main.php';
    
    public static $secretId  = '';
    public static $secretKey = '';
    public static $appid     = '';
    public static $userid    = '';
    public static $expired   = '';
    /**
     * 初始化
     * @see \yii\base\Object::init()
     */    
    public function init(){
        session_start();
        if(!isset($_SESSION['user'])){ header("Location:login");exit();}
        $this->_message  = Yii::$app->params['message'];
        self::$secretId  = Yii::$app->params['youtu']['SECRET_ID'];
        self::$secretKey = Yii::$app->params['youtu']['SECRET_KEY'];
        self::$appid     = Yii::$app->params['youtu']['APPID'];
        self::$userid    = Yii::$app->params['youtu']['USER_ID'];
        self::$expired   = Yii::$app->params['youtu']['EXPIRED'];
        //$this->redis = new Redis();
        //$this->redis->connect(Yii::$app->params['redis']['host'],Yii::$app->params['redis']['port']);
    }

    /**
     *  页面返回JSON数据
     */
    public function _exit($code, $param = NULL) {
        $msg = $this->_message[$code];
        exit(json_encode(array('msg' => $msg, 'code' => $code, 'data' => $param)));
        
    }
    /**
     * Curl 请求方法
     * @param string $url
     * @param array $data
     * @param string $method 
     * @return Response
     */
    public function curl($url, $data = NULL, $method = 'post') {
        $curl = new curl\Curl();
        if ($method=='post' && $data !== NULL) 
            $response = $curl->setOption(CURLOPT_POSTFIELDS, $data)->post($url);
        if ($method=='get' && $data === NULL)  
            $response = $curl->get($url);
        
        return $response;
    }

    /**
     * 随机获取字符串
     * @param number $length
     * @return string
     */
    function rand_str( $length = 16 ) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $str = '';
        for ( $i = 0; $i < $length; $i++ ) {
            $str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return $str;
    }
    /**
     * 签名函数
     * @return string    签名
     */
    public static function appSign() {
        //$plainText = 'a='.self::$appid.'&k='.self::$secretId.'&e='.self::$expired.'&t='.time().'&r='.rand().'&u='.$userid;
        $plainText = 'u='.self::$userid.'a='.self::$appid.'&k='.self::$secretId.'&e='.self::$expired.'&t='.time().'&r='.rand().'&f=';
        $bin = hash_hmac("SHA1", $plainText, self::$secretKey, true) . $plainText;
        return base64_encode($bin);
    }
    /**
     * send http request
     * @param  array $rq http请求信息
     *                   url        : 请求的url地址
     *                   method     : 请求方法，'get', 'post', 'put', 'delete', 'head'
     *                   data       : 请求数据，如有设置，则method为post
     *                   header     : 需要设置的http头部
     *                   host       : 请求头部host
     *                   timeout    : 请求超时时间
     *                   cert       : ca文件路径
     *                   ssl_version: SSL版本号
     * @return string    http请求响应
     */
    public static function send($rq) {
        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $rq['url']);
        switch (true) {
            case isset($rq['method']) && in_array(strtolower($rq['method']), array('get', 'post', 'put', 'delete', 'head')):
                $method = strtoupper($rq['method']);
                break;
            case isset($rq['data']):
                $method = 'POST';
                break;
            default:
                $method = 'GET';
        }
        $header = isset($rq['header']) ? $rq['header'] : array();
        $header[] = 'Method:'.$method;
        $header[] = 'User-Agent:'.Yii::$app->params['youtu']['PKG_VERSION'].'('.php_uname().')';
        isset($rq['host']) && $header[] = 'Host:'.$rq['host'];
        curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, $method);
        isset($rq['timeout']) && curl_setopt($curlHandle, CURLOPT_TIMEOUT, $rq['timeout']);
        isset($rq['data']) && in_array($method, array('POST', 'PUT')) && curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $rq['data']);
        $ssl = substr($rq['url'], 0, 8) == "https://" ? true : false;
        if( isset($rq['cert'])){
            curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER,true);
            curl_setopt($curlHandle, CURLOPT_CAINFO, $rq['cert']);
            curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST,2);
            if (isset($rq['ssl_version'])) {
                curl_setopt($curlHandle, CURLOPT_SSLVERSION, $rq['ssl_version']);
            } else {
                curl_setopt($curlHandle, CURLOPT_SSLVERSION, 4);
            }
        }else if( $ssl ){
            curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER,false);   //true any ca
            curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST,1);       //check only host
            if (isset($rq['ssl_version'])) {
                curl_setopt($curlHandle, CURLOPT_SSLVERSION, $rq['ssl_version']);
            } else {
                curl_setopt($curlHandle, CURLOPT_SSLVERSION, 4);
            }
        }
        $ret = curl_exec($curlHandle);
        //$_httpInfo = curl_getinfo($curlHandle);//捕捉请求信息或异常。
        curl_close($curlHandle);
        return $ret;
    }
}
